package ee.roosideSoda.backend.model.dao.postgresqlimplementations;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

import ee.roosideSoda.backend.database.ConnectionManager;
import ee.roosideSoda.backend.model.dao.TiimDAO;
import ee.roosideSoda.backend.model.data.Tiim;

public class TiimDAOPostgresqlImpl implements TiimDAO
{
	Logger logger = Logger.getLogger(TiimDAOPostgresqlImpl.class);
	Connection dbConnection;
	String sql;
	PreparedStatement preparedStatement;
	Statement statement;
	ResultSet resultSet;
	private final int WARNING_NO_ROWS_AFFECTED = 0;
	private int rowsAffected;
	
	public TiimDAOPostgresqlImpl(Connection dbConnection)
	{	
		this.dbConnection = dbConnection;
	}

	
	@Override
	public int sisestaTiim(Tiim tiim) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "INSERT INTO Tiimid " + 
				"(tiimiNimi, punkte) " + 
				"VALUES (?, ?)";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			
			preparedStatement.setString	(1, tiim.getTiimiNimi());
			preparedStatement.setInt	(2, tiim.getPunkte());
			
			logger.info(preparedStatement.toString());
			rowsAffected = preparedStatement.executeUpdate();
			
			if (rowsAffected == 1)
			{
				resultSet = preparedStatement.getGeneratedKeys();
				resultSet.next(); //answer consist only 1 row, so move the cursor just once to start to process the result
				int newId = resultSet.getInt(1); // 1, because identifiers are held in the first column 
				tiim.setTiimID(newId);
				return rowsAffected;
			}
			else
			{
				System.out.println("No rows affected!");
				logger.info("Unsuccessful insertion to a database: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			return WARNING_NO_ROWS_AFFECTED;
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}

	@Override
	public Tiim saaTiimIDJargi(int tiimID) 
	{
		resultSet = null;
		Tiim tiimiAndmedAndmebaasist = null;
		sql = "SELECT * FROM Tiimid WHERE tiimID = ?";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
						sql,
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY
					);
			//filling the placeholders 
			preparedStatement.setInt(1, tiimID);
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of a received data set (so it can start to read and process data)
			resultSet.beforeFirst();
			
			if (resultSet.next())
			{
				//setObject() is used, when column or field value in java, can also be null.
				tiimiAndmedAndmebaasist = new Tiim();
				tiimiAndmedAndmebaasist.setTiimID(resultSet.getInt("tiimID"));
				tiimiAndmedAndmebaasist.setTiimiNimi(resultSet.getString("tiimiNimi"));
				tiimiAndmedAndmebaasist.setPunkte(resultSet.getInt("punkte"));
			}
		}
		catch (SQLException e) 
		{
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return tiimiAndmedAndmebaasist;
	}

	@Override
	public int uuendaTiimiNime(int tiimID, String uusTiimiNimi) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "UPDATE Tiimid " + 
				"SET tiimiNimi = ? " + 
				"WHERE tiimID = ?"; 
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql);
			
			preparedStatement.setString	(1, uusTiimiNimi);
			preparedStatement.setInt	(2, tiimID);
			
			rowsAffected = preparedStatement.executeUpdate();
			
			
			if (rowsAffected == 1)
			{
				logger.info("Update sucessful: " + preparedStatement.toString());
				return rowsAffected;
			}
			else
			{
				logger.error("Update was unsuccesful: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
			return WARNING_NO_ROWS_AFFECTED;		
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}

	@Override
	public int uuendaTiimiPunktiseisu(int tiimID, int lisatavadPunktid)
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "UPDATE Tiimid " + 
				"SET punkte = (SELECT punkte FROM Tiimid WHERE tiimID = ?) + (?) " + 
				"WHERE tiimID = ?"; 
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql);
			
			preparedStatement.setInt(1, tiimID);
			preparedStatement.setInt(2, lisatavadPunktid);
			preparedStatement.setInt(3, tiimID);
			
			rowsAffected = preparedStatement.executeUpdate();
			
			
			if (rowsAffected == 1)
			{
				logger.info("Update sucessful: " + preparedStatement.toString());
				return rowsAffected;
			}
			else
			{
				logger.error("Update was unsuccesful: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
			return WARNING_NO_ROWS_AFFECTED;		
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}
	
	@Override
	public int saaTiimiPunktiseis(int tiimID) 
	{
		resultSet = null;
		int tiimiPunktiseis = -1;
		sql = "SELECT punkte FROM Tiimid WHERE tiimID = ?";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
						sql,
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY
					);
			//filling the placeholders 
			preparedStatement.setInt(1, tiimID);
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of a received data set (so it can start to read and process data)
			resultSet.beforeFirst();
			
			if (resultSet.next())
			{
				tiimiPunktiseis = (resultSet.getInt("punkte"));
			}
		}
		catch (SQLException e) 
		{
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return tiimiPunktiseis;
	}
}
